﻿BPBK = function () {

}
BPBK.columns = new Array("Mã Bill", "Loại Bpbk", "Tên Bpbk", "Trạng Thái", "Khách Hàng", "Đơn Vị");
BPBK.fieldText = new Array("MaBill","TenBpbk", "MaTrangThai", "MaKhachHang", "MaDonVi");
var numberPage = 1;
BPBK.MaBill = -1;
BPBK.isInsert = 0;
BPBK.arrays = new Array();
BPBK.Init = function () {
    BPBK.arrays = new Array();
    var obj;
    obj = new CheckField("TenBpbk", 1, "ErrTenBpbk");
    BPBK.Add(obj);
    obj = new CheckField("TrongLuong", 2, "ErrTrongLuong");
    BPBK.Add(obj);
    obj = new CheckField("NgayGoi", 1, "ErrNgayGoi");
    BPBK.Add(obj);
}

BPBK.Add = function (obj) {
    if (BPBK.arrays.contains(obj) == false) {
        BPBK.arrays.push(obj);
    }
}
BPBK.GetMoney = function (trongluong) {
    var arrs = Constants.Read("banggia");
    console.dir(arrs);
    for (var i = 0; i < arrs.length; i++) {
        var obj = arrs[i];        
        if (parseFloat(obj.Tu) <= parseFloat(trongluong) && parseFloat(trongluong) <= parseFloat(obj.Den)) {
            return parseFloat(obj.DonGia);
        }
    }
    return 0;
}

BPBK.Insert = function () {
    var serviceUrl = Constants.service + "insertTblBpbks";
    var strDate = $("#NgayGoi").val();
    var parseDate = Constants.parseDate(strDate, "-");
    var now = "/Date(" + parseDate.getTime() + "+0700)/";
    var trongLuong = parseFloat($("#TrongLuong").val());
    var donGia = BPBK.GetMoney(trongLuong);
    if ($("#DonGia").val() == "" || $("#DonGia").val() == undefined || $("#DonGia").val() == null) {

    }
    else {
        donGia = parseFloat($("#DonGia").val());
    }
    if (Constants.OnSubmit(BPBK.arrays) == false) {
        return false;
    }
    var user = Constants.Read('adminLocalStorage'); //JSON.parse(localStorage.getItem('adminLocalStorage'));    
    var MaNguoiDung = user.key;
    var data = {
        MaBill: $("#MaBill").val(),
        MaLoaiBpbk: $("#MaLoaiBpbk").val(),
        TenBpbk: $("#TenBpbk").val(),
        MaTrangThai: $("#MaTrangThai").val(),
        MaKhachHang: $("#MaKhachHang").val(),
        MaDonVi: $("#MaDonVi").val(),
        DaXoa: false,
        TrongLuong: trongLuong,
        NgayGoi: now,
        MaNguoiDung: MaNguoiDung,
        DonGia: donGia,
        ThanhTien: donGia
    };
    var json = JSON.stringify({ item: data });
    $.ajax({
        type: "Post",
        url: serviceUrl, // Location of the service
        data: json, //Data sent to server
        contentType: "application/json", // content type sent to server
        dataType: "json", //Expected data format from server
        cache: false,
        success: function (msg) {
            BPBK.GetData();
            Constants.Cancel();
        },
        error: function (err) {
            // When Service call fails
        }
    });
}

BPBK.Delete = function (id) {    
    var data = {
        MaBill: id
    };
    var json = JSON.stringify({ item: data });
    a = confirm(Constants.messDelete);
    if (a == false) {
        return;
    }
    var serviceUrl = Constants.service + "deleteTblBpbks";
    $.ajax({
        type: "Post",
        url: serviceUrl, // Location of the service
        data: json, //Data sent to server
        contentType: "application/json", // content type sent to server
        dataType: "json", //Expected data format from server
        cache: false,
        success: function (data) {
            BPBK.GetData();
        },
        error: function (err) {
            // When Service call fails
        }
    });
}

BPBK.UpdateItem = function () {
    if (Constants.OnSubmit(BPBK.arrays) == false) {
        return false;
    }
    var serviceUrl = Constants.service + "updateTblBpbks";
    var strDate = $("#NgayGoi").val();
    var parseDate = Constants.parseDate(strDate, "-");
    var now = "/Date(" + parseDate.getTime() + "+0700)/";
    var trongLuong = parseFloat($("#TrongLuong").val());
    var donGia = BPBK.GetMoney(trongLuong);
    var user = Constants.Read('adminLocalStorage'); //JSON.parse(localStorage.getItem('adminLocalStorage'));    
    var MaNguoiDung = user.key;
    var data = {
        MaBill: $("#MaBill").val(),
        MaLoaiBpbk: $("#MaLoaiBpbk").val(),
        TenBpbk: $("#TenBpbk").val(),
        MaTrangThai: $("#MaTrangThai").val(),
        MaKhachHang: $("#MaKhachHang").val(),
        MaDonVi: $("#MaDonVi").val(),
        DaXoa: false,
        TrongLuong: trongLuong,
        NgayGoi: now,
        MaNguoiDung: MaNguoiDung,
        DonGia: donGia,
        ThanhTien: donGia
    };
    var json = JSON.stringify({ item: data });
    $.ajax({
        type: "Post",
        url: serviceUrl, // Location of the service
        data: json, //Data sent to server
        contentType: "application/json", // content type sent to server
        dataType: "json", //Expected data format from server
        cache: false,
        success: function (msg) {
            BPBK.GetData();
            Constants.Cancel();
        },
        error: function (err) {
            // When Service call fails
        }
    });
}

BPBK.CreateTable = function (r, nbpage, data) {
    var myTable = BPBK.TitleColumns(BPBK.columns);
    myTable += BPBK.DataColumnsOftr(data, r, nbpage);
    myTable += "</table>";
    $("#div_list").children().remove();
    $("#div_list").append(myTable);
    $("#div_content").show();
}

BPBK.Search = function () {
    var serviceUrl = Constants.service + "getFindTblBpbks";
    var data = {
        value: $("#search").val()
    };
    var json = JSON.stringify({ item: data });
    $.ajax({
        type: "Post",
        url : serviceUrl,
        data: json,
        contentType: "application/json",
        dataType: "json",
        cache: false,
        success: function (msg) {
            var results = msg.getFindTblBpbksResult;
            if (results != null && results.length > 0) {
                BPBK.CreateTable(Constants.rows, numberPage, results);
            }
            else {
                $("#div_list").children().remove();
                $("#div_list").html(Constants.find);
            }
        }
    });
}

BPBK.GetData = function () {
    var serviceUrl = Constants.service + "getAllTblBpbks";
    var data = { url: window.location.host };
    var json = JSON.stringify({ item: data });
    BPBK.MaBill = -1;
    BPBK.isInsert = 0;
    $.ajax({
        type: "Post",
        url: serviceUrl, // Location of the service
        data: json, //Data sent to server
        contentType: "application/json", // content type sent to server
        dataType: "json", //Expected data format from server
        cache: false,
        success: function (msg) {
            var results = msg.getAllTblBpbksResult;
            var dataTables = results;
            BPBK.CreateTable(Constants.rows, numberPage, dataTables);
        },
        error: function (err) {
            // When Service call fails
        }
    });
}

BPBK.TitleColumns = function (_columns) {
    var myColumns = "<table class=\"rounded-corner\">";
    myColumns += "<thead><tr>"; //<th class=\"rounded-company\" scope=\"col\"></th>
    for (var i = 0; i < _columns.length; i++) {
        myColumns += "<th class=\"rounded\" scope=\"col\">" + _columns[i] + "</th>";
    }
    myColumns += "<th class=\"rounded\" scope=\"col\">Edit</th>";
    myColumns += "<th class=\"rounded-q4\" scope=\"col\">Delete</th>";
    myColumns += "</tr></thead>";
    var n = _columns.length + 1;
    myColumns += "<tfoot><tr><td class=\"rounded-foot-left\" colspan=\"" + n + "\"><em> </em></td>";
    myColumns += "<td class=\"rounded-foot-right\">&nbsp;</td>";
    myColumns += "</tr></tfoot>";
    return myColumns;
}

BPBK.DataColumnsOftr = function (data, rs, _numberPage) {
    var myDataColumns = "<tbody>";
    var n = data.length;
    var j = (_numberPage - 1) * rs;
    var r = rs;
    for (var i = j; i < r && i < n; i++) {
        var id = data[i].MaBill;
        myDataColumns += "<tr onclick='return BPBK.OnClick(" + id + ")'" + " id=\"" + id + "\">";     
        myDataColumns += "<td>" + data[i].MaBill + "</td>"
        myDataColumns += "<td>" + data[i].TenLoaiBpbk + "</td>"
        myDataColumns += "<td>" + data[i].TenBpbk + "</td>"
        myDataColumns += "<td>" + data[i].TenTrangThai + "</td>"
        myDataColumns += "<td>" + data[i].TenKhachHang + "</td>"
        myDataColumns += "<td>" + data[i].TenDonVi + "</td>"        
        myDataColumns += "<td><img onclick='return BPBK.EditItem("+ id +")' border=\"0\" title=\"\" alt=\"" + id + "\" src=\"images/user_edit.png\"></td>";
        myDataColumns += "<td><a class=\"ask\" ><img onclick='return BPBK.Delete(" + id + ")' border=\"0\" title=\"\" alt=\""
         + id + "\" src=\"images/trash.png\"></a></td></tr>";
    }
    myDataColumns += "</tbody>";
    return myDataColumns;
}

BPBK.OnClick = function (id) {
    BPBK.MaBill = id;
    $(".active").removeClass();
    $("#" + id).addClass("active");
    return false;
}

BPBK.OnClickEdit = function () {
    if (BPBK.MaBill == -1) {
        alert(Constants.selectEdit);
    }
    else
        BPBK.EditItem(BPBK.MaBill);
}

BPBK.OnClickDelete = function () {
    if (BPBK.MaBill == -1) {
        alert(Constants.selectDelete);
    }
    else
        BPBK.Delete(BPBK.MaBill);
}

BPBK.EditItem = function (obj_id) { 
    var temp_item = "Modules/bpbk/Edit";   
    $("#dialog").empty();
    $.ajax({
        url: temp_item + ".htm",
        success: function (data) {
            $('#dialog').append(data);
            $("#dialog").dialog("open");
            $("#dialog").dialog({ title: "Sửa" });
            Constants.GetLoaiBpbk("MaLoaiBpbk");
            Constants.GetTrangThai("MaTrangThai");
            Constants.GetKhachHang("MaKhachHang");
            Constants.GetDonVi("MaDonVi");
            BPBK.GetItem(obj_id);            
        }
    });
}

BPBK.GetItem = function (id) {
    var serviceUrl = Constants.service + "getItemByIdTblBpbk";
    var data = { MaBill: id };
    var json = JSON.stringify({ item: data });
    $.ajax({
        type: "Post",
        url: serviceUrl, // Location of the service
        data: json, //Data sent to server
        contentType: "application/json", // content type sent to server
        dataType: "json", //Expected data format from server
        cache: false,
        success: function (msg) {
            var result = msg.getItemByIdTblBpbkResult;
            if (result != null && result != undefined) {
                $("#MaBill").val(result.MaBill);
                $("#MaLoaiBpbk").val(result.MaLoaiBpbk);
                $("#TenBpbk").val(result.TenBpbk);
                $("#MaTrangThai").val(result.MaTrangThai);
                $("#MaKhachHang").val(result.MaKhachHang);
                $("#MaDonVi").val(result.MaDonVi);
                $("#TrongLuong").val(result.TrongLuong);
                $("#DonGia").val(result.ThanhTien);
                var dateAsFromServerSide = result.NgayGoi.replace(")/", "");
                var parsedDate = new Date(parseInt(dateAsFromServerSide.substr(6)));
                $("#NgayGoi").val(Constants.formatDate(parsedDate));
            }
        },
        error: function (err) {
            // When Service call fails
        }
    });
}

BPBK.Clear = function () {
    Constants.clearAll(BPBK.fieldText);
}


BPBK.AddNewItem = function () {
    var temp_item = "Modules/bpbk/AddNew";
    BPBK.isInsert = 1;
    $("#dialog").empty();
    $.ajax({
        url: temp_item + ".htm",
        success: function (data) {
            $('#dialog').append(data);
            $("#dialog").dialog("open");
            $("#dialog").dialog({ title: "Thêm Mới" });
            BPBK.getMaTblBpbks();
            Constants.GetLoaiBpbk("MaLoaiBpbk");
            Constants.GetTrangThai("MaTrangThai");
            Constants.GetKhachHang("MaKhachHang");
            Constants.GetDonVi("MaDonVi");
        }
    });
}

BPBK.getMaTblBpbks = function () {
    // 
    var serviceUrl = Constants.service + "getMaTblBpbks";
    $.ajax({
        type: "Post",
        url: serviceUrl, // Location of the service
        //data: json, //Data sent to server
        contentType: "application/json", // content type sent to server
        dataType: "json", //Expected data format from server
        cache: false,
        success: function (msg) {
            var result = msg.getMaTblBpbksResult;
            $("#MaBill").val(result);
        },
        error: function (err) {
            // When Service call fails
        }
    });
}

BPBK.registerEvent = function () {
    $("#NgayGoi").datepicker({ dateFormat: "dd-mm-yy" });
    $("#MaBill").keypress(function (event) {
        if (event.keyCode == 13) {
            event.preventDefault();
            $("#TenBpbk").focus();
        }
    });
    $("#TenBpbk").keypress(function (event) {
        if (event.keyCode == 13) {
            event.preventDefault();
            $("#TrongLuong").focus();
        }
    });
    $("#TrongLuong").blur(function () {
        try {
            var trongLuong = parseFloat($("#TrongLuong").val());
            var money = BPBK.GetMoney(trongLuong);
            $("#DonGia").val(money);
            event.preventDefault();
            $("#NgayGoi").focus();
        }
        catch (e) { }
    });
    $("#TrongLuong").keypress(function (event) {
        if (event.keyCode == 13) {
            var trongLuong = parseFloat($("#TrongLuong").val());
            var money = BPBK.GetMoney(trongLuong);
            $("#DonGia").val(money);
            event.preventDefault();
            $("#NgayGoi").focus();
        }
    });
    $("#NgayGoi").keypress(function (event) {
        if (event.keyCode == 13) {
            event.preventDefault();
            if (BPBK.isInsert == 1) {
                BPBK.Insert();
            }
            else {
                BPBK.UpdateItem();
            }
        }
    });
}
$(document).ready(function () {
    BPBK.GetData();
    BPBK.Init();
    var user = Constants.Read('adminLocalStorage'); //JSON.parse(localStorage.getItem('adminLocalStorage'));    
    $("#search").keypress(function (event) {
        if (event.keyCode == 13) {
            event.preventDefault();
            BPBK.Search();
        }
    });
    $("#search_on").click(function (event) {
        event.preventDefault();
        BPBK.Search();
    });

});
